package com.smcdd.cdb.dbo.cdb_dbo.ui.activity;

import android.app.Dialog;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.event.SaoMiao;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.CdbInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DialogUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 作者：Administrator on 2017/7/19 13:01
 * 邮箱：zhanghuaiha@gmail.com
 */

public class InputActivity extends BaseActivity {

    private TextView input;
    private EditText et;
    private ImageView add_back;
    private static final int REQUEST_CODE = 5;
    private static final int SAO_CODE = 6;
    private static final int WITHDRAW = 7;
    private static final int HARDWARE_FAULT = 8;
    private static final int GREEN_LIGHTING = 9;
    private static final int UPDATE_CDB = 10;
    private static final int GET_FIRMWARE = 11;
    private static final int SEND_FACTORY = 12;
    private int send_factory;
    private Dialog progressDialog;

    @Override
    public void initView() {
        add_back = (ImageView) findViewById(R.id.add_back);
        input  = (TextView) findViewById(R.id.input);
        et  = (EditText) findViewById(R.id.input_id);
    }

    @Override
    public void initData() {
        send_factory = getIntent().getIntExtra("send_factory", 0);

    }

    @Override
    public void initListener() {
        add_back.setOnClickListener(v -> finish());

        input.setOnClickListener(v -> {
            String trim = et.getText().toString().trim().toUpperCase();
            String s = stringFilter(trim);
            System.out.println(trim.length()+trim+"!!!"+s);
            if (TextUtils.isEmpty(trim)) {
                ToastUtil.showToast("设备ID不能为空");
            }else if (trim.length() != 12) {
                ToastUtil.showToast("设备ID长度不一致");
            }else if(!trim.equals(s)) {
                ToastUtil.showToast("设备ID不匹配");
                }else {
                get_input(trim);
            }
        });
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                String s1 = et.getText().toString().trim().toUpperCase();
//                String str = stringFilter(s1);
//                if(!s1.equals(str)){
//                    et.setText(str);
//                    //设置新的光标所在位置
//                    et.setSelection(str.length());
//                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public static String stringFilter(String str)throws PatternSyntaxException {
        // 只允许字母和数字
        String   regEx  =  "[^a-zA-Z0-9]";
        Pattern   p   =   Pattern.compile(regEx);
        Matcher m   =   p.matcher(str);
        return   m.replaceAll("").trim();
    }

    //^[0-9A-Z]+$


    public void get_input(String alias){
        dialog();
        String versionName = ObtainVersion.getVersionName(this);
        String eid = App.SP.getString("id", "");
        String udid = App.SP.getString("udid", "");
        String tiem = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",tiem);
        map.put("v",versionName);
        map.put("i", NetWorkCodeInfo.GETCDB_INFO_INPUT);
        map.put("udid",udid);
        map.put("eid",eid);
        map.put("alias",alias);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getCdb_info_input(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<CdbInfo>>() {
                    @Override
                    public void success(BaseResponseEntity<CdbInfo> cdbInfoBaseResponseEntity) {
                        if (cdbInfoBaseResponseEntity.code == 200) {
                            switch (send_factory) {
                                case SEND_FACTORY:
                                    //寄回工厂
                                    EventBus.getDefault().post(new SaoMiao(SEND_FACTORY,alias));
                                    finish();
                                    break;
                                case WITHDRAW:
                                    //设备撤回
                                    EventBus.getDefault().post(new SaoMiao(WITHDRAW,alias));
                                    finish();
                                    break;
                                case SAO_CODE:
                                    //设备撤回
                                    EventBus.getDefault().post(new SaoMiao(SAO_CODE,alias));
                                    finish();
                                    break;
                                case REQUEST_CODE:
                                    //设备撤回
                                    EventBus.getDefault().post(new SaoMiao(REQUEST_CODE,alias));
                                    finish();
                                    break;
                                default:
                                    break;
                            }
                            progressDialog.dismiss();
                        }else {
                            progressDialog.dismiss();
                            DialogUtils.ClickDialog(InputActivity.this,cdbInfoBaseResponseEntity.message,true);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        progressDialog.dismiss();
                        DialogUtils.ClickDialog(InputActivity.this,InputActivity.this.getString(R.string.error_date),true);
                    }
                });
    }

    public void dialog(){
        progressDialog = new Dialog(this,R.style.progress_dialog);
        progressDialog.setContentView(R.layout.dialog);
        progressDialog.setCancelable(true);
        progressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        TextView msg = (TextView) progressDialog.findViewById(R.id.id_tv_loadingmsg);
        msg.setText("正在提交中.");
        progressDialog.show();
    }



    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_input;
    }
}
